package com.baidu.job;

import java.util.List;
import java.util.Random;
import java.util.UUID;

import com.baidu.basic.DateUtils;
import com.baidu.dwr.CloudPush;
import com.baidu.emus.CloudType;
import com.baidu.emus.CronType;
import com.baidu.model.BDUser;
import com.baidu.model.CloudCount;
import com.baidu.model.DictContent;
import com.baidu.model.MyTB;
import com.baidu.model.Reply;
import com.baidu.model.ReplyContent;
import com.baidu.model.ReplyRec;
import com.baidu.model.SysUser;
import com.baidu.util.BaiDuApi;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

/**
 * 执行任务内容（统一管理）
 * @author libs
 * 2015-12-30 10:36
 */
public class MainJobContent extends Controller{
	
	/**
	 * 签到任务
	 */
	public static void sign(){
		try {
			List<MyTB> list = MyTB.dao.querySignTB(null);
			Long successCount = 0L;
			Long successExp = 0L;
			for (MyTB tb : list) {
				MyTB bean = BaiDuApi.api.signDo(tb, tb.getStr("bduss"));
				if(StrKit.notBlank(bean.getStr("code")) && (bean.getStr("code")).equals("0")){
					//签到成功  更新统计表
					successCount++;
					if(bean.getInt("countSignNum") != null && bean.getInt("countSignNum") > 1){
						successExp = successExp + 8L;
					}else{
						successExp = successExp + 6L;
					}
				}
				bean.update();
			}
			if(successCount > 0){
				CloudCount cloud = CloudCount.dao.findCountByType(CloudType.signCount.getCode(), successCount, successExp);
				CloudPush.statistics(cloud.getLong("count"),cloud.getLong("exp"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 每天刷新一次贴吧列表和用户列表
	 * @throws Exception 
	 */
	public static void refreshJob() throws Exception{
		//删除未绑定贴吧的用户
		List<SysUser> userList = SysUser.dao.queryUnBindUser();
		if(userList != null && userList.size() > 0){
			for (SysUser sysUser : userList) {
				sysUser.set("isDeleted", true).update();
			}
		}
		List<BDUser> bdList = BDUser.dao.findAll();
		for (BDUser bdUser : bdList) {
			String bduss = bdUser.getStr("bduss");
			List<MyTB> list = BaiDuApi.api.getMyLikedTB(bduss);
			List<MyTB> list2 = MyTB.dao.queryTbs(bdUser.getStr("guid"));
			for (MyTB myTB : list2) {
			    Boolean flag = false;
			    if(list != null && list.size() != 0){
			        for (int i = 0; i < list.size(); i++) {
			            if(myTB.getStr("name").equals(list.get(i).getStr("name"))){
			                flag = true;
			                break;
			            }
			            
			        }
			    }
			    if(!flag){
			        myTB.delete();
			    }
			}
			for (MyTB tb : list) {
			    if(tb.getInt("fid") != null && StrKit.notBlank(bdUser.getStr("guid"))){
			        tb.set("bdGuid", bdUser.get("guid"));
			        MyTB.dao.saveTB(tb);
			    }
			}
		}
	}
	
	/**
	 * 回帖任务
	 * @param cronType
	 */
	public static void reply(final Integer cronType){
		List<Reply> list = null;
		if(cronType == CronType.replyMinute.getCode()){
			list = Reply.dao.queryReplyList(1);
		}else if(cronType == CronType.replyHour.getCode()){
			list = Reply.dao.queryReplyList(0);
		}
		if(list != null && list.size() != 0){
			String content = "";
			for (Reply reply : list) {
				if(reply.getInt("content") == 1){//自定义
					ReplyContent rc = ReplyContent.dao.findFirst("select * from reply_content where bdGuid = ? order by rand() limit 1",reply.getStr("bdGuid"));
					content = rc.getStr("content");
				}else{//默认随机
					List<DictContent> dc = DictContent.dao.queryRandomByNum(1);
					content = dc.get(0).getStr("content");
				}
				String[] tds = reply.getStr("tid").split(",");
				String[] fids = reply.getStr("fid").split(",");
				String[] tbNames = reply.getStr("tbNames").split(",");
				for (int i = 0; i < fids.length; i++) {
					try {
						if("0".equals(tds[i])){//随机回复
							List<String> ids = BaiDuApi.api.getIndexTList(reply.getStr("bduss"), tbNames[i], -1);
							String tidRandom = null;
							if(ids != null && list.size() != 0){
								Random r = new Random();
								tidRandom = ids.get(r.nextInt(ids.size()));
								String result = BaiDuApi.api.reply(reply.getStr("bduss"), tidRandom, fids[i].toString(),
										tbNames[i], content, reply.getInt("clientType"));
								ReplyRec rec = new ReplyRec();
								rec.set("guid", UUID.randomUUID().toString());
								rec.set("msg", result);
								rec.set("url", "http://tieba.baidu.com/p/" + tidRandom);
								rec.set("replyGuid", reply.getStr("guid"));
								rec.set("replyTime", DateUtils.realTime("Asia/Shanghai"));
								rec.save();
							}
						}else{
							String result = BaiDuApi.api.reply(reply.getStr("bduss"), tds[i], fids[i].toString(),
									tbNames[i], content, reply.getInt("clientType"));
							ReplyRec rec = new ReplyRec();
							rec.set("guid", UUID.randomUUID().toString());
							rec.set("msg", result);
							rec.set("url", "http://tieba.baidu.com/p/" + tds[i]);
							rec.set("replyGuid", reply.getStr("guid"));
							rec.set("replyTime", DateUtils.realTime("Asia/Shanghai"));
							rec.save();
						}
					} catch (Exception e) {
					}	
				}
			}
		}
	}
	
	/**
	 * 清空今天之前的回帖记录
	 */
	public static void clearRec() {
		ReplyRec.dao.clearRec();
	}
	
	/**
	 * 贴吧机器人 cron
	 * @param type 
	 * @throws Exception 
	 */
	public static void robotCron(String type) throws Exception {
	   BaiDuApi.api.getmsg("a", "type");
	}
	
}
